<?php

require(__DIR__.'/../vendor/autoload.php');
require_once(__DIR__.'/core/core.php');
require_once(__DIR__.'/config/config.php');

use Phine\Path\Path;

function endsWith($haystack, $needle)
{
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }

    return (substr($haystack, -$length) === $needle);
}

function isRaw($file, $config){
  $pathInfo = pathinfo($file);
  $ext = $pathInfo['extension'];
  $filename = $pathInfo['filename'];

  if(!in_array($ext, array('jpg', 'jpeg', 'png', 'gif'))) return false;

  foreach ($config["transform"] as $t) {
    if(endsWith($filename, $t['suffix'])){
      return false;
    }
  }

  return true;
}

function findFiles($config)
{
  $toManipulate = array();
  $uploadDir = $config["upload_dir"];
  $d = dir($uploadDir);

  while (false !== ($entry = $d->read())) {
    $file = Path::join(array($uploadDir, $entry));

    if(is_file($file) && isRaw($file, $config)){
      array_push($toManipulate, $file);
    }
  }

  $d->close();

  return $toManipulate;
}

function main($config){
  $toManipulate = findFiles($config);
  foreach ($toManipulate as $singleFile) {
    ImageServer::manipulate($singleFile);
  }
}

main($config);
/* End of file transform-all.php */
